import { dictToWhere } from '@/utils/sqlUtils'

const Base = require('../entities/Base')

const AccountDao = {
    table: "account"
}

AccountDao.initialForm = (login, usage) => {
    if (!usage) {
        usage = ""
    }
    return JSON.parse(JSON.stringify({
        id: 0,
        account: "",
        password: "",
        platform: "",
        usageScope: usage,
        login: Boolean(login),
        storage: "",
        cookie: "",
        enable: true,
        loginRegex: "",
        loginUrl: "",
        selectors: "",
    }))
}

AccountDao.rules = () => {
    return {}
}

AccountDao.fixBoolRow = (row) => {
    row.enable = Boolean(row.enable)
    row.login = Boolean(row.login)
    return row
}

AccountDao.fetchByID = async (id) => {
    let whereSql = "where id = " + id
    return await Base.fetchOne(AccountDao.table, whereSql)
}

AccountDao.fetchAll = async (usageScope, platformId) => {
    if (!platformId) {
        platformId = -1
    }
    if (!usageScope) {
        usageScope = -1
    }
    let whereDict = {
        platform: platformId,
        usageScope: usageScope
    }
    let whereSql = dictToWhere(whereDict)
    return await Base.fetchWhere(AccountDao.table, whereSql)
}

AccountDao.save = async (obj) => {
    return await Base.save(AccountDao.table, obj)
}

AccountDao.delete = async (id) => {
    return await Base.delete(AccountDao.table, id)
}

export { AccountDao }